/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package qserver;

import fsktms.dispatcher.Dispatcher;
import APIs.AccountAPIs;
import APIs.ChatAPIs;
import APIs.QuerryAPIs;
import APIs.RelationAPIs;
import chat.ChatMessage;
import chat.ChatServer;
import chat.room.ChatRoom;
import dalfactory.SDALFactory;
import fsktms.messagemanager.IMessageManager;
import fsktms.request.IRequest;
import fsktms.request.api.RequestAPIManager;
import fsktms.server.*;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import utils.DataRow;
import utils.DataTable;

/**
 *
 * @author salm
 */
public class QServer implements ServerEventListener
{
    private NetServer netServer;
    private Dispatcher dispatchServer;
    private RequestAPIManager requestAPIs;
    private ChatServer chatServer;
    
    public QServer(int port) throws IOException
    {
        this.netServer = new NetServer(port);
        this.dispatchServer = new Dispatcher(netServer);
        this.netServer.getListeners().add(this);
        
        this.chatServer = new ChatServer(this.netServer);
        this.initRooms();
        this.dispatchServer.getMessageListeners().put(ChatMessage.CHAT_MESSAGE_MAGICKEY, this.chatServer);
        
        this.requestAPIs = new RequestAPIManager(netServer);
        this.addAPIs();
        this.dispatchServer.getMessageListeners().put(IRequest.REQUEST_MESSAGE_MAGICKEY, requestAPIs);
    }
    
    @Override
    public void clientConnected(NetServer sv, IMessageManager mm)
    {
        System.out.println(mm.getAddress() + " connected!!!");
    }

    @Override
    public void clientDisconnected(NetServer sv, IMessageManager mm)
    {
        System.out.println(mm.getAddress() + " disconnected!!!");
        this.chatServer.leaveAccount(mm.getAddress());
    }
    
    public void startServer()
    {
        (new Thread(this.netServer)).start();
        this.dispatchServer.run();
    }

    private void addAPIs()
    {
        this.requestAPIs.addAPI(new AccountAPIs());
        this.requestAPIs.addAPI(new RelationAPIs());
        this.requestAPIs.addAPI(new QuerryAPIs());
        this.requestAPIs.addAPI(new ChatAPIs(this.chatServer));
    }
    
    private void initRooms()
    {
        try {
            DataTable dtRooms = SDALFactory.getInstance().getRoom().getAllRoom();
            if (dtRooms != null)
            {
                for (DataRow row : dtRooms)
                {
                    this.chatServer.addRoom(new ChatRoom(row.get("RoomID"), row.get("Name")));
                }
            }
        } catch (RemoteException ex) {
            Logger.getLogger(QServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}